使用python解决TSP(旅行商问题)

这段时间,因为要交一篇关于旅行商问题的作业,所以在github上搜索了一下,觉得用python解决比较方便,所以给大家简单的介绍一下如何使用所给的代码:

用python实现的TSP源码:  GitHub链接:https://github.com/eldrtimo/python-salesman    百度云盘链接:链接:http://pan.baidu.com/s/1i57BhGx 密码:2w4b

这段代码使用python3实现的,可以在windows的dos环境下运行,而且还要借助于numpy(它是一种开源的python数值计算扩展)。所以必须要安装python3 和 相应的numpy;


1.安装python3

2.配置python的环境变量:把python安装路径添加到path环境变量中即可;

3.安装numpy;如果已安装python,会自动识别出python安装路径,直接点next即可。

这一切准备工作结束后,然后进入dos环境(win+r,输入cmd回车),进入源代码(python-salesman-master)所在目录,我这里是E盘,输入以下命令运行即可:


运行的命令:python main.py -nfi tspfiles


运行的结果部分截图如下:



命令中的参数介绍:

python main.py --help

usage: main.py [-h] [-n] [-f] [-i] [-p] PATH [PATH ...]

Parse TSP files and calculate paths using simple algorithms.

positional arguments:
  PATH               Path to directory or .tsp file. If PATH is a directory,
                     run on all .tsp files in the directory.

optional arguments:
  -h, --help         show this help message and exit
  -n, --nearest      calculate distance traveled by nearest neighbor heuristic
  -f, --furthest     calculate distance traveled by furthest insertion
                     heuristic
  -i, --in-order     calculate the distance traveled by the in-order-tour
                     [1..n,1]
  -p, --print-tours  print explicit tours

  • 2
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
TSP问题是指旅行商问题,即在给定的一些城市之间寻找一条最短的路径,使得每个城市恰好被访问一次,最终回到起点城市。Python可以使用多种算法来解决TSP问题,其中比较常用的是遗传算法和模拟退火算法。 遗传算法的基本思想是通过模拟生物进化过程来搜索最优解。具体实现中,可以将每个城市看作一个基因,将所有城市的排列看作一个染色体,然后通过交叉、变异等操作来不断优化染色体,最终得到最优解。 模拟退火算法则是通过模拟物质在高温下的运动来搜索最优解。具体实现中,可以将每个城市看作一个状态,然后通过随机游走的方式来不断优化状态,最终得到最优解。 以下是一个使用遗传算法解决TSP问题的示例代码: ```python import random # 城市坐标 cities = [(60, 200), (180, 200), (80, 180), (140, 180), (20, 160), (100, 160), (200, 160), (140, 140), (40, 120), (100, 120), (180, 100), (60, 80), (120, 80), (180, 60), (20, 40), (100, 40), (200, 40), (20, 20), (60, 20), (160, 20)] # 计算两个城市之间的距离 def distance(city1, city2): return ((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2) ** 0.5 # 计算染色体的适应度 def fitness(chromosome): total_distance = 0 for i in range(len(chromosome) - 1): total_distance += distance(cities[chromosome[i]], cities[chromosome[i+1]]) total_distance += distance(cities[chromosome[-1]], cities[chromosome[0]]) return 1 / total_distance # 初始化种群 def init_population(population_size, chromosome_length): population = [] for i in range(population_size): chromosome = list(range(chromosome_length)) random.shuffle(chromosome) population.append(chromosome) return population # 选择操作 def selection(population, fitness_values): total_fitness = sum(fitness_values) probabilities = [fitness_value / total_fitness for fitness_value in fitness_values] selected_indices = random.choices(range(len(population)), weights=probabilities, k=2) return population[selected_indices[0]], population[selected_indices[1]] # 交叉操作 def crossover(parent1, parent2): child = [-1] * len(parent1) start_index = random.randint(0, len(parent1) - 1) end_index = random.randint(start_index, len(parent1) - 1) for i in range(start_index, end_index + 1): child[i] = parent1[i] j = 0 for i in range(len(parent2)): if parent2[i] not in child: while child[j] != -1: j += 1 child[j] = parent2[i] return child # 变异操作 def mutation(chromosome, mutation_rate): for i in range(len(chromosome)): if random.random() < mutation_rate: j = random.randint(0, len(chromosome) - 1) chromosome[i], chromosome[j] = chromosome[j], chromosome[i] return chromosome # 遗传算法主函数 def genetic_algorithm(population_size, chromosome_length, max_generations): population = init_population(population_size, chromosome_length) for generation in range(max_generations): fitness_values = [fitness(chromosome) for chromosome in population] best_chromosome = population[fitness_values.index(max(fitness_values))] print('Generation {}: Best fitness = {}'.format(generation, max(fitness_values))) new_population = [best_chromosome] while len(new_population) < population_size: parent1, parent2 = selection(population, fitness_values) child = crossover(parent1, parent2) child = mutation(child, 0.01) new_population.append(child) population = new_population return best_chromosome # 测试 best_chromosome = genetic_algorithm(100, len(cities), 1000) print('Best chromosome:', best_chromosome) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值